import spock.lang.Specification

/**
 * Created at 2017/11/1 19:32
 * @author gongweixin
 */
class MapReduceExample extends Specification {

    def "test map"() {
        def result1 = [1: 11, 2: 22].collect {it ->
            it.key
        }

        def result2 = [1: 11, 2: 22].collect {k,v ->
            k
        }

        expect:
        [1, 2] == result1
        [1, 2] == result2
    }

    def "test reduce"() {
        def result1 = [1,2,3].inject(0, { sum, it ->
            sum + it
        })

        def result2 = [[1,2], [3]].inject([], {list, value ->
            list.addAll(value)
            list
        })

        def result3 = [[1,2], [3]].inject([]) {list, value ->
            list.addAll(value)
            list
        }

        expect:
        6 == result1
        [1,2,3] == result2
        [1,2,3] == result3
    }

    def "test list to map"() {
        def result = [1, 2, 3].collectEntries {
            [it, it]
        }

        expect:
        [1: 1, 2: 2, 3: 3] == result
    }

    def "test map to one result"() {
        expect:
        [1, 2, 3] == [a:[1], b:[2], c:[3]].inject([], { list, it ->
            list + it.value
        })
    }

    def "test map exception"() {
        expect:
        [10, 5, 2] == [1, 2, 0, 5].collect {
            10 / it as int
        }
    }

    def "test map map reduce list"() {
        expect:
        [1: [1, 3], 0: [2, 4]] == [1, 2, 3, 4].groupBy {it%2}
        [1, 2, 3, 4].sort() == [1, 2, 3, 4].groupBy {it%2}.collectMany {it.value}.sort()
    }
}
